// pages/demo2/demo2.js
function formatDate(date) {
  const y = date.getFullYear();
  const m = (date.getMonth() + 1).toString().padStart(2, '0');
  const d = date.getDate().toString().padStart(2, '0');
  const h = date.getHours().toString().padStart(2, '0');
  const min = date.getMinutes().toString().padStart(2, '0');
  const s = date.getSeconds().toString().padStart(2, '0');
  return `${y}/${m}/${d} ${h}:${min}:${s}`;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartList: [],
    totalPrice: 0,
    allSelected: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadCart();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  loadCart() {
    let cartList = wx.getStorageSync('cartList') || [];
    // 增加selected字段，默认true
    cartList = cartList.map(item => ({ ...item, selected: item.selected !== undefined ? item.selected : true }));
    this.setData({ cartList });
    this.updateAllSelected();
    this.calcTotal();
  },

  // 切换全选
  toggleAllSelect() {
    const allSelected = !this.data.allSelected;
    const cartList = this.data.cartList.map(item => ({ ...item, selected: allSelected }));
    this.setData({ allSelected, cartList });
    wx.setStorageSync('cartList', cartList);
    this.calcTotal();
  },

  // 切换单个选中状态
  toggleSelect(e) {
    const id = e.currentTarget.dataset.id;
    const cartList = this.data.cartList.map(item =>
      item.id === id ? { ...item, selected: !item.selected } : item
    );
    this.setData({ cartList });
    wx.setStorageSync('cartList', cartList);
    this.updateAllSelected();
    this.calcTotal();
  },

  // 判断是否全选
  updateAllSelected() {
    const allSelected = this.data.cartList.length > 0 && this.data.cartList.every(item => item.selected);
    this.setData({ allSelected });
  },

  // 改变数量
  changeCount(e) {
    const id = e.currentTarget.dataset.id;
    const type = e.currentTarget.dataset.type;
    let cartList = this.data.cartList.map(item => {
      if (item.id === id) {
        let count = item.count;
        if (type === 'plus') count++;
        if (type === 'minus' && count > 1) count--;
        return { ...item, count };
      }
      return item;
    });
    this.setData({ cartList });
    wx.setStorageSync('cartList', cartList);
    this.calcTotal();
  },

  removeItem(e) {
    const id = e.currentTarget.dataset.id;
    let cartList = this.data.cartList.filter(item => item.id !== id);
    wx.setStorageSync('cartList', cartList);
    this.loadCart();
  },

  calcTotal() {
    let totalPrice = 0;
    this.data.cartList.forEach(item => {
      if (item.selected) {
        totalPrice += item.price * item.count;
      }
    });
    this.setData({ totalPrice });
  },

  // 结算按钮点击事件
  onSettle() {
    // 获取已选中的商品
    const selectedItems = this.data.cartList.filter(item => item.selected);
    if (selectedItems.length === 0) {
      wx.showToast({
        title: '请选择要结算的商品',
        icon: 'none'
      });
      return;
    }
    // 获取本地订单列表
    let orderList = wx.getStorageSync('orderList') || [];
    // 新订单对象
    const newOrder = {
      id: Date.now(),
      status: '交易成功',
      items: selectedItems,
      total: selectedItems.reduce((sum, item) => sum + item.price * item.count, 0),
      time: formatDate(new Date())
    };
    orderList.unshift(newOrder);
    wx.setStorageSync('orderList', orderList);
    // 移除已结算商品
    const remainCart = this.data.cartList.filter(item => !item.selected);
    wx.setStorageSync('cartList', remainCart);
    wx.showToast({
      title: '结算成功！',
      icon: 'success'
    });
    this.loadCart();
  }
})